<template>
    <div>
        <!--卡片-->
        <el-card class="box-card">
            <!--定义面包屑-->
            <el-breadcrumb separator=">">
                <el-breadcrumb-item :to="{ path: '/homePage' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item></el-breadcrumb-item>
                <el-breadcrumb-item></el-breadcrumb-item>
            </el-breadcrumb>
            <el-divider></el-divider>
            <!--表单的搜索框
                 :model="双向绑定表单的数据"
            -->
            <el-form :inline="true" :model="queryUserData"  class="demo-form-inline">
                <el-form-item >
                    <el-input v-model="queryUserData.name" placeholder="请输入维修厂名"></el-input>
                </el-form-item>

                <el-form-item >
                    <el-cascader
                            :options="options"
                            v-model="queryUserDataAddress"
                            placeholder="请选择维修厂地址"
                    >
                    </el-cascader>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="initMaintainTable()">查询</el-button>
                    <el-button type="primary" @click="handleAdd()">添加</el-button>
                </el-form-item>
            </el-form>

            <!--数据表格-->
            <template>
                <el-table
                        :data="tableData"
                        :border="true"
                        stripe
                        style="width: 100%">
                    <el-table-column
                            prop="name"
                            label="修理厂">
                    </el-table-column>

                    <el-table-column
                            prop="address"
                            label="地址">
                    </el-table-column>
                    <el-table-column
                            prop="phone"
                            label="联系电话">
                    </el-table-column>

                    <el-table-column
                            prop="addtime"
                            label="当前用户创建的时间">
                    </el-table-column>

                    <!--营业状态-->
                    <el-table-column
                            prop="status"
                            label="营业状态">
                        <template slot-scope="scope">
                            <el-switch
                                    v-model="scope.row.status"
                                    active-color="#13ce66"
                                    active-value="0"
                                    inactive-value="1"
                                    inactive-color="#ff4949"
                                    @change="statusChange(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>


                    <!--操作栏-->
                    <el-table-column label="操作" >
                        <template slot-scope="scope">
                            <!-- 修改 -->
                            <el-button type="primary" icon="el-icon-edit"  @click="handleEdit(scope.row)"></el-button>

                            <!--查询维修记录-->
                            <el-button type="info"  icon="el-icon-search"  @click="handleSelectRecord(scope.row)"></el-button>

                            <!-- 删除 -->
                            <el-button type="danger" icon="el-icon-delete" @click="handleDelet(scope.row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[3, 5, 7, 15]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </template>

            <!-- 修改用户的角色 /新增角色-->
            <el-dialog
                    title="提示"
                    :visible.sync="dialogFormVisible"
                    width="30%"
            >
                <!--model:表单数据-->
                <el-form  label-width="120px" :model="showMainForm"  ref="showMainForm">
                    <el-form-item label="维修厂" prop="name">
                        <el-input v-model="showMainForm.name"></el-input>
                    </el-form-item>

                    <el-form-item label="地址">
                        <el-cascader
                                size="medium"
                                :options="options"
                                v-model="selectedOptions"
                                @change="handleChange">
                        </el-cascader>
                    </el-form-item>

                    <el-form-item label="联系电话">
                        <el-input v-model="showMainForm.phone"></el-input>
                    </el-form-item>

                    <!--picker-options="pickerOptions0"  限制今天以后不能选-->
                    <el-form-item label="创建时间">
                        <el-input v-model="showMainForm.addtime"
                                  value-format="yyyy-M-d"
                                  editable=false></el-input>
                    </el-form-item>


                    <el-form-item label="营业状态">
                        <el-select v-model="showMainForm.status" placeholder="请选择营业状态">
                            <el-option label="开业" value="0"></el-option>
                            <el-option label="打样" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmEdit('showMainForm')">确 定</el-button>
              </span>
            </el-dialog>

            <el-drawer
                    :visible.sync="dialogMaintainShopRecordCarInfo"
                    direction="rtl"
                    size="90%"
            >
                <el-form :inline="true" :model="queryCarInfoData"  class="demo-form-inline">
                    <el-form-item >
                        <el-input v-model="queryCarInfoData.orderId" placeholder="请输入订单号"></el-input>
                    </el-form-item>

                    <el-form-item >
                        <el-input v-model="queryCarInfoData.carId" placeholder="请输入车牌号"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="initMaintainRecordTable()">查询</el-button>
                        <el-button type="primary" @click="AddOrder()">添加</el-button>
                    </el-form-item>
                </el-form>

                <template>
                    <el-table
                            :data="tableData1"
                            :border="true"
                            stripe
                            style="width:100%">
                        <el-table-column
                                prop="orderId"
                                label="订单号">
                        </el-table-column>

                        <el-table-column
                                prop="carId"
                                label="牌照">
                        </el-table-column>

                        <el-table-column
                                prop="car"
                                label="汽车名">
                        </el-table-column>

                        <el-table-column
                                prop="recordInfo"
                                label="故障描述">
                        </el-table-column>

                        <el-table-column
                                prop="badParts"
                                label="损坏零件">
                        </el-table-column>

                        <el-table-column
                                prop="damagedStatus"
                                label="受损程度">
                        </el-table-column>

                        <el-table-column
                                prop="recordDate"
                                label="维修日期">
                        </el-table-column>

                        <el-table-column
                                prop="finish"
                                label="维修完毕日期">
                        </el-table-column>

                        <!--修理完毕状态-->
                        <el-table-column
                                prop="recordStatus"
                                label="修理完毕状态">
                            <template slot-scope="scope">
                                <el-switch
                                        v-model="scope.row.recordStatus"
                                        active-color="#13ce66"
                                        :active-value="0"
                                        :inactive-value="1"
                                        inactive-color="#ff4949"
                                        @change="statusChange1(scope.row)">
                                </el-switch>
                            </template>
                        </el-table-column>

                        <el-table-column
                                prop="maintenancePrice"
                                label="维修价格">
                        </el-table-column>

                        <!--操作栏-->
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <!-- 修改 -->
                                <el-button type="primary" icon="el-icon-edit"  @click="editOrder(scope.row)"></el-button>
                                <!-- 删除 -->
                                <el-button type="danger" icon="el-icon-delete" @click="deletOrder(scope.row)"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination
                            @size-change="handleSizeChange1"
                            @current-change="handleCurrentChange1"
                            :current-page="currentPage1"
                            :page-sizes="[3, 5, 7, 15]"
                            :page-size="pageSize1"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total1">
                    </el-pagination>
                </template>
            </el-drawer>

            <!--添加维修单-->
            <el-dialog
                    title="提示"
                    :visible.sync="orderDialogVisible"
                    width="30%"
                    center>
                <el-form ref="form" :model="orderForm" label-width="100px">
                    <el-form-item label="汽车名">
                        <el-input v-model="orderForm.car"></el-input>
                    </el-form-item>
                    <el-form-item label="车牌照">
                        <el-input v-model="orderForm.carId"></el-input>
                    </el-form-item>

                    <el-form-item label="故障描述">
                        <el-input type="textarea" v-model="orderForm.recordInfo"></el-input>
                    </el-form-item>

                    <el-form-item label="损坏零件">
                        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                        <div style="margin: 15px 0;"></div>
                        <el-checkbox-group v-model="checkedBadParts" @change="handleCheckedPartsChange">
                            <el-checkbox v-for="part in parts" :label="part" :key="part">{{part}}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="损坏程度">
                        <el-select v-model="orderForm.damagedStatus" placeholder="请选择受损程度">
                            <el-option label="无"  :value="0"></el-option>
                            <el-option label="轻微" :value="1"></el-option>
                            <el-option label="普通" :value="2"></el-option>
                            <el-option label="严重" :value="3"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="维修日期">
                            <el-input v-model="orderForm.recordDate"
                                      value-format="yyyy-M-d"
                                      editable=false
                                      ></el-input>
                    </el-form-item>
                    <el-form-item label="维修完毕状态" >
                        <el-select v-model="orderForm.recordStatus" placeholder="维修状态">
                            <el-option label="维修中" :value="0"></el-option>
                            <el-option label="维修完毕" :value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="维修价格">
                        <el-input v-model="orderForm.maintenancePrice"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="confirmOrderForm(orderForm)">添加订单</el-button>
                        <el-button @click="orderDialogVisible=false">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    // import { regionDataPlus } from 'element-china-area-data';
/**
* CodeToText是个大对象，属性是区域码，属性值是汉字 用法例如：CodeToText['110000']输出北京市
* TextToCode是个大对象，属性是汉字，属性值是区域码 用法例如：TextToCode['北京市'].code输出110000,TextToCode['北京市']['市辖区'].code输出110100,TextToCode['北京市']['市辖区']['朝阳区'].code输出110105
*/
    import { regionData , CodeToText, TextToCode } from 'element-china-area-data'
    const partsOptions = ['车灯', '漆面', '叶子板', '前/后保险杠', '换机油', '换胎', '发动机故障', '其他'];
    export default {
        name: "maintainShop",
        data() {
            return {

                //搜索框表单
                queryUserData: {
                    name:"",
                    address:""
                },
                //维修厂数据表格
                tableData: [],
                //当前页条数
                pageSize:5,
                //当前页
                currentPage:1,
                //总条数
                total: 0,



                statusOp : ["营业","打样"],

                queryCarInfoData:{},


                //新增，修改提交表单
                showMainForm:{
                    name:"",
                    address:'',
                    phone:"",
                    addtime:"",
                    status:""
                },
                //弹出新增修改维修厂表单
                dialogFormVisible: false,
                //弹出新增/修改维修厂维修记录表
                dialogMaintainShopRecordCarInfo:false,



                //维修厂维修记录表
                tableData1:[],
                //当前页条数
                pageSize1:5,
                //当前页
                currentPage1:1,
                //总条数
                total1: 0,
                params: {
                    id:"",
                    recordStatus:"",
                },

                //时间范围（今天以后不能选）
                pickerOptions0: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },



                params: {
                    id: 0,
                    status: 0,
                },

                params1:{},

                //三级联动
                options: regionData,
                dzBox:[],
                selectedOptions: [],
                dzTable:{},
                //下拉框
                form:{
                    provinces:"",
                    city:"",
                    area:""
                },
                queryUserDataAddress:[],

                //弹出新增修改维修订单表
                orderDialogVisible:false,
                orderForm:{
                    carId:"",
                    shopId:0,
                    id:"",
                    car:"",
                    recordInfo:"",
                    maintenancePrice:"",
                    recordDate:"",
                    badParts:[],
                    damagedStatus:0,
                    recordStatus:0,
                },



                checkAll: false,
                checkedBadParts:[],
                parts: partsOptions,
                isIndeterminate: true,
                shopID :0,

            }
        },
        methods:{
            handleCheckAllChange(val) {
                this.checkedBadParts = val ? partsOptions : [];
                this.isIndeterminate = false;
            },
            handleCheckedPartsChange(value) {
                this.orderForm.badParts = value;
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.parts.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.parts.length;
            },

            editOrder(r){
                this.orderDialogVisible= true;
                this.orderForm.damagedStatus =  r.damagedStatus;
                this.orderForm.recordDate = r.recordDate;
                this.orderForm.recordStatus = r.recordStatus;
                this.checkedBadParts = r.badParts.split(",");
                this.orderForm.carId = r.carId;
                this.orderForm = r;
            },
            //添加订单
            AddOrder(){
                this.orderForm={};
                this.orderForm.shopId = this.shopID;
                const nowDate = new Date();
                let date = {
                    year: nowDate.getFullYear(),
                    month: nowDate.getMonth() + 1,
                    date: nowDate.getDate(),
                };
                let systemDate = date.year + '-' + date.month + '-' + date.date;
                this.orderForm.recordDate = systemDate;
                this.checkedBadParts=[];
                this.orderForm.badParts = this.checkedBadParts;
                this.orderDialogVisible= true;
            },
            deletOrder(row){
                var that = this;
                this.$axios.put(`clms-cmms/tbMaintainShopRecordCarInfo/deleteRecordCarInfo/${row.id}`).then(function (r) {
                    if (r.data.code === 2000){
                        that.$message.success(r.data.message);
                    }
                    that.initMaintainRecordTable();
                });
            },
            confirmOrderForm(data){
               this.orderForm.badParts = this.orderForm.badParts.toString();
               console.log(data)
                let that = this
               this.$axios.put(`clms-cmms/tbMaintainShopRecordCarInfo/updateRecordCarInfo`,data).then(function (r) {
                   console.log(r)
                   that.orderDialogVisible= false;
                   that.initMaintainRecordTable();
               })
            },
            //初始化表格
            initMaintainTable(){
                let that  = this;
                console.log(this.showMainForm.address )
                let a = this.queryUserDataAddress.toString();
                this.queryUserData.address =a.substring(0,a.length-1);
                console.log(this.queryUserData.address)
                this.$axios.post(`clms-cmms/tbMaintainShop/getAllMaintainShop/${this.currentPage}/${this.pageSize}`,this.queryUserData).then(function (r) {
                    //console.log(r.data.result.AllMaintainShop.records);
                    //容器封装
                    that.dzBox = r.data.result.AllMaintainShop.records;
                    console.log(that.dzBox);
                    //调用循环遍历方法
                    that.aroundCodeText(that.dzBox);
                    // for (let i=0;i<that.dzBox.length;i++){
                    //     //得到地址码
                    //     let dzValue = that.dzBox[i].address;
                    //     //转成数组
                    //     let dzValues = dzValue.split(",");
                    //     let dz;
                    //     if (dzValues[1] != null && dzValues[2] != null) {
                    //         dz = CodeToText[dzValues[0]] + '/' + CodeToText[dzValues[1]] + '/' + CodeToText[dzValues[2]]
                    //     } else {
                    //         if (dzValues[1] != null) {
                    //             dz = CodeToText[dzValues[0]] + '/' + CodeToText[dzValues[1]]
                    //         } else {
                    //             dz = CodeToText[dzValues[0]]
                    //         }
                    //     }
                    //     console.log(dz)
                    //     that.dzBox[i].address = dz;
                    // }
                    //console.log(that.dzBox)
                    console.log(that.queryUserData.address);
                    that.total = r.data.result.total;
                    that.tableData = r.data.result.AllMaintainShop.records;
              })
            },

            //店铺 维修车辆表
            initMaintainRecordTable(){
                var that = this;
                console.log(this.queryCarInfoData)
                this.$axios.put(`clms-cmms/tbMaintainShop/searchMaintainShopCarInfo/${this.currentPage1}/${this.pageSize1}`,this.queryCarInfoData).then(function (r){
                    that.tableData1 = r.data.result.page.records;
                    that.total1 = r.data.result.total1;
                    console.log(that.tableData1)
                })
            },



            //修改/新增按钮
            handleEdit(r) {
                this.dialogFormVisible = true;
                console.log(r)
                let strings = r.address.split("/");
                // //console.log(strings);
                this.form.provinces = strings[0];
                this.form.city = strings[1];
                this.form.area = strings[2];
                console.log(this.form)
                //console.log(this.form.provinces)
                //下拉框回显
                this.selectedOptions=[
                    TextToCode[this.form.provinces].code,
                    TextToCode[this.form.provinces][this.form.city].code,
                    TextToCode[this.form.provinces][this.form.city][this.form.area].code]

                // this.showMainForm.address = this.selectedOptions;
                var c= JSON.stringify(r);
                var d=JSON.parse(c);
                this.showMainForm = d;

               // console.log(row)
            },
            handleAdd() {
                this.dialogFormVisible = true;
                //console.log(row)
                this.showMainForm = {};
                this.selectedOptions=[];
                const nowDate = new Date();
                let date = {
                    year: nowDate.getFullYear(),
                    month: nowDate.getMonth() + 1,
                    date: nowDate.getDate(),
                };
                let systemDate = date.year + '/' + date.month + '/' + date.date;
                this.showMainForm.addtime =systemDate;
            },
            confirmEdit(data){
                console.log(this.$refs[data].validate)  //获取表单数据
                this.$refs[data].validate((valid) => {
                    var that = this;
                    if (valid) {
                        //console.log(data)
                        console.log(this.showMainForm)
                        this.showMainForm.address=this.selectedOptions.toString();
                        this.$axios.put(`clms-cmms/tbMaintainShop/upDataById`,this.showMainForm).then(function (result) {
                            that.dialogFormVisible = false;
                            that.$message({
                                message: result.data.result.message,
                                type: 'success'
                            });
                            that.initMaintainTable();
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            //循环便利解码地址
            aroundCodeText(a){
                for (let i=0;i<a.length;i++){
                    //得到地址码
                    let dzValue = a[i].address;
                    //转成数组
                    let dzValues = dzValue.split(",");
                    let dz;
                    if (dzValues[1] != null && dzValues[2] != null) {
                        dz = CodeToText[dzValues[0]] + '/' + CodeToText[dzValues[1]] + '/' + CodeToText[dzValues[2]]
                    } else {
                        if (dzValues[1] != null) {
                            dz = CodeToText[dzValues[0]] + '/' + CodeToText[dzValues[1]]
                        } else {
                            dz = CodeToText[dzValues[0]]
                        }
                    }
                    console.log(dz)
                    this.dzBox[i].address = dz;
                }
            },

            //有多少条
            handleSizeChange(v){
                this.pageSize = v;
                this.initMaintainTable();
            },
            //当前页码
            handleCurrentChange(v){
                this.currentPage = v;
                this.initMaintainTable();
            },
            handleSizeChange1(v){
                this.pageSize1 = v;
                this.initMaintainRecordTable(this.sid);
            },
            handleCurrentChange1(v){
                this.currentPage1 = v;
                this.initMaintainRecordTable(this.sid);
            },

            handleChange(value) {
                console.log(value)
                // console.log(this.tableData.address);
                //把地址数组转化字符串       去掉逗号.replace(/,/g, "")
                let a = value.toString();
                //去掉最后一个字符逗号
                this.showMainForm.address = a;
                //console.log( this.showMainForm.address)
                //console.log(value)
            },

            //逻辑删除
            handleDelet(row){
                let that = this;
                this.$axios.post(`clms-cmms/tbMaintainShop/deletMaintainShop/${row.id}`).then(function (r) {
                    if (r.data.code == 200){
                        that.$message.success(r.data.object);
                    }
                    that.initMaintainTable();
                })
            },
            //查看车辆维修记录按钮
            handleSelectRecord(row){
               this.dialogMaintainShopRecordCarInfo = true;
               this.shopID = row.id;
               this.queryCarInfoData.id = row.id;
               this.initMaintainRecordTable();
            },
            statusChange(row){
                this.params.id = row.id;
                this.params.status = row.status;
                this.$axios.put(`clms-cmms/tbMaintainShop/updateStatus`,this.params).then( result => {
                    if (result.data.code == 200) {
                        this.$message.success(result.data.message);
                        this.initMaintainTable()
                    } else {
                        this.$message.error(result.data.message)
                    }
                })
            },
            statusChange1(row){
                var that =this;
                const nowDate = new Date();
                let date = {
                    year: nowDate.getFullYear(),
                    month: nowDate.getMonth() + 1,
                    date: nowDate.getDate(),
                    hours: nowDate.getHours()+1,       //获取当前小时数(0-23)
                    minutes:nowDate.getMinutes(),     //获取当前分钟数(0-59)
                };
                let systemDate = date.year + '-' + date.month + '-'  + date.date +'  '+date.hours+':'+date.minutes;
                if (row.recordStatus === 0){
                    this.params1.id = row.id;
                    this.params1.recordStatus = row.recordStatus;
                    this.params1.finish = systemDate;
                    this.$axios.post(`clms-cmms/tbMaintainShop/updateRecordStatus`,this.params1).then( result => {
                        if (result.data.code == 2000) {
                            that.$message.success(result.data.message);
                            that.initMaintainRecordTable()
                        } else {
                            this.$message.error(result.data.message)
                        }
                    })
                }else if (row.recordStatus === 1){
                    this.params1.id = row.id;
                    this.params1.recordStatus = row.recordStatus;
                    this.params1.finish = "";
                    this.$axios.post(`clms-cmms/tbMaintainShop/updateRecordStatus`,this.params1).then( result => {
                        if (result.data.code == 2000) {
                            that.$message.success(result.data.message);
                            that.initMaintainRecordTable()
                        } else {
                            that.$message.error(result.data.message)
                        }
                    })
                }

            },
        },
        created(){
            this.initMaintainTable();
        }
    }
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>